package com.pyrsana.faith.membership

import grails.plugins.springsecurity.Secured

import org.springframework.dao.DataIntegrityViolationException

class AccountController {
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    
    def springSecurityService
    
    def index() {
        redirect(action: "show", params: params)
    }
    
    @Secured(['ROLE_ADMIN', 'ROLE_DIRECTOR'])
    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)        
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }
    
    def register() {
        def userInstance = new User(params)
        [userInstance: userInstance, profileInstance: userInstance.profile]
    }

    def save() {
        def userInstance = new User(params)
        
        if (userInstance) {
            userInstance.enabled = true
            if (userInstance.profile.save() && userInstance.save(flush: true)) {
                // Default to user role:
                SecUserSecRole.create(userInstance, SecRole.findByAuthority('ROLE_USER'))
                
                if (!springSecurityService.isLoggedIn()) {
                    flash.message = message(code: 'account.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])
                    redirect(controller: 'login', action: 'auth', id: userInstance.id)
                }
                else {
                    flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])
                    redirect(action: "show", id: userInstance.id)
                }
            }
        }
        render(view: "register", model: [userInstance: userInstance, profileInstance: userInstance.profile])
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def show() {
        def userId = springSecurityService.currentUser.authorities.find {it.authority == 'ROLE_ADMIN' || it.authority == 'ROLE_DIRECTOR' } && params.id ? params.id : springSecurityService.currentUser.id
        if (!userId) {
            redirect(action: "register")
        }
        else {
            def userInstance = User.get(userId)
            if (!userInstance) {
    			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), userId])
                redirect(action: "register")
                return
            }
    
            [userInstance: userInstance]
        }
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def edit() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance, profileInstance: userInstance.profile]
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def update() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (userInstance.version > version) {
                userInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'user.label', default: 'User')] as Object[],
                          "Another user has updated this User while you were editing")
                render(view: "edit", model: [userInstance: userInstance])
                return
            }
        }

        // Do not replace with an empty password:
        if (params.password == '') {
            params.remove('password')
        }
        
        userInstance.properties = params

        if (!userInstance.profile.save() || !userInstance.save(flush: true)) {
            render(view: "edit", model: [userInstance: userInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])
        redirect(action: "show", id: userInstance.id)
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def delete() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        try {
            userInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
	
	@Secured(['ROLE_ADMIN, ROLE_DIRECTOR'])
	def roles() {
		Map<Object, Object> model = [:]
		model['user'] = params.uid ? User.get(params.uid) : null
		SecRole role =  params.rid ? SecRole.get(params.rid) : null
		model['users'] = role ? User.findAll(authorities?.contains(role)) : null
		model['allRoles'] =  SecRole.list()
		
		return model
	}
	
	@Secured(['ROLE_ADMIN, ROLE_DIRECTOR'])
	def addRoleToUser() {
		User user = User.get(params.id)
		
		if (user) {
			SecRole role = SecRole.get(params.role_id)
			if (role) {
				if (!user.getAuthorities().contains(role)) {
					SecUserSecRole.create(user, role)
				}
				else {
					flash.message = user.username + ' already has role ' + role.authority
				}
			}
			else {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'secRole.label', default: 'Role'), params.role_id])
			}
		}
		else {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
		}
		
		redirect(action: "roles")
	}
	
	@Secured(['ROLE_ADMIN, ROLE_DIRECTOR'])
	def removeRoleFromUser() {
		User user = User.get(params.id)
		
		if (user) {
			SecRole role = SecRole.get(params.role_id)
			if (role) {
				flash.message = 'Role ' + role.authority + ' removed from ' + user.username 
			}
			else {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'secRole.label', default: 'Role'), params.role_id])
			}
		}
		else {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
		}
		
		redirect(action: "roles")
	}
}
